package com.bjdl.collectTool.project.web.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.benjaminwan.ocrlibrary.OcrResult;
import com.bjdl.collectTool.project.web.common.exception.CustomException;
import com.bjdl.collectTool.project.web.domain.dto.GroupInfo;
import com.bjdl.collectTool.project.web.service.AnalyzeService;
import com.bjdl.collectTool.project.web.utils.ResourceFileUtils;
import io.github.mymonstercat.Model;
import io.github.mymonstercat.ocr.InferenceEngine;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

@Service
public class analyzeServiceImpl implements AnalyzeService {


    @Override
    public void parseZipFile(MultipartFile file) throws Exception {
        List<String> folderNames = new ArrayList<>();
        // 创建临时解压目录
        File extractDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "zip_extract_" + DateUtil.today().replaceAll("-", ""));
        if (!extractDir.exists()) {
            extractDir.mkdirs();
        }

        // 创建与原文件夹同名的子文件夹
        File exportDir = new File("E:" + File.separator + "群截图提取处理" + DateUtil.today().replaceAll("-", ""));
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }

        // 创建错误日志文件夹和文件
        File errorLogDir = new File(exportDir, "error_logs");
        if (!errorLogDir.exists()) {
            errorLogDir.mkdirs();
        }
        String errorLogFileName = "error_log_" + DateUtil.today().replaceAll("-", "") + ".txt";
        File errorLogFile = new File(errorLogDir, errorLogFileName);
        PrintWriter errorLogWriter = new PrintWriter(new FileWriter(errorLogFile, true));

        // 用于记录最初解压的文件路径
        Set<String> originalFilePaths = new HashSet<>();

        try {
            java.io.File tempFile = java.io.File.createTempFile("temp", ".zip");
            file.transferTo(tempFile);

            // 压缩包文件路径
            String zipFilePath = tempFile.getAbsolutePath();
            // 打开压缩文件
            ZipFile zipFile = new ZipFile(zipFilePath, Charset.forName("gbk"));

            // 加载 Excel 文件
            final String templateUrl = "templates/wxfxqtq.xlsx";
            Workbook hssfWorkbook = getWorkbook(templateUrl);
            Iterator<Sheet> sheetIterator = hssfWorkbook.sheetIterator();
            while (sheetIterator.hasNext()) {
                Sheet next = sheetIterator.next();

                Row row = next.getRow(0);
                Cell cell = row.getCell(0);
                String stringCellValue = cell.getStringCellValue();
                cell.setCellValue(stringCellValue.replace("date", DateUtil.today()));
            }

            // 用于存储每个供电公司的群信息
            Map<String, List<GroupInfo>> groupInfoMap = new HashMap<>();

            // 用于记录已经出现过的图片名
            Set<String> imgNameSet = new HashSet<>();
            // 用于记录每个原始图片名对应的重复次数
            Map<String, Integer> imgNameCountMap = new HashMap<>();

            // 遍历压缩文件中的所有条目
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File targetFile = new File(extractDir, entry.getName());
                if (entry.isDirectory()) {
                    targetFile.mkdirs();
                    String folderName = entry.getName();
                    folderNames.add(folderName);
//                    System.out.println("找到文件夹: " + folderName);
                } else {

                    originalFilePaths.add(targetFile.getAbsolutePath());

                    String[] parts = entry.getName().split("/");
                    String part0 = parts[0];
                    String gdgsName = parts[1].replace("供电公司", "");
                    String gdsName = parts[2];
                    String imgName = parts[3];//如果名字相同,则用数字区分

                    //测试数据20250221/大兴/北臧村供电所/测试供电所-北臧村供电所.jpg
                    System.out.println("==================获取到的图片名字为==================" + imgName);
                    if (isImageFile(imgName)) {
                        try (InputStream inputStream = zipFile.getInputStream(entry);
                             OutputStream outputStream = new FileOutputStream(targetFile)) {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                        }
                        // 传递图片在本地的绝对路径
                        String resStr = imgParser(targetFile.getAbsolutePath());

                        if (ObjectUtil.isNotEmpty(resStr)) {
                            String[] split = resStr.split("_");
                            String groupName = split[0];
                            String groupSize = split[1];

                            // 如果名字相同，则用数字区分
                            int count = imgNameCountMap.getOrDefault(gdsName + groupName, 0) + 1;
                            imgNameCountMap.put(gdsName + groupName, count);
                            if (count > 1) {
                                groupName = groupName + "" + count;
                            }

                            // 获取图片所在文件夹路径
                            String parentFolderPath = gdgsName + "\\" + targetFile.getParentFile().getName();

                            File renamedParentDir = new File(exportDir, parentFolderPath);
                            if (!renamedParentDir.exists()) {
                                renamedParentDir.mkdirs();
                            }
                            // 获取图片扩展名
                            String fileExtension = imgName.substring(imgName.lastIndexOf("."));
                            String[] split1 = imgName.split("\\.");
                            // 构建重命名后的文件路径
                            File renamedFile = new File(renamedParentDir, split1[0] + "——" + groupName + fileExtension);
                            try (InputStream input = new FileInputStream(targetFile);
                                 OutputStream output = new FileOutputStream(renamedFile)) {
                                byte[] buf = new byte[4096];
                                int bytesRead;
                                while ((bytesRead = input.read(buf)) != -1) {
                                    output.write(buf, 0, bytesRead);
                                }
                            }
                            System.out.println("图片重命名为: " + renamedFile.getName() + " 并保存到: " + parentFolderPath);

                            // 存储群信息
                            groupInfoMap.computeIfAbsent(gdgsName, k -> new ArrayList<>())
                                    .add(new GroupInfo(gdsName, groupName, groupSize, imgName));
                        } else {
                            System.err.println("未找到图片名字");
                            errorLogWriter.println("未找到图片名字: " + gdgsName + "——" + gdsName + "——" + imgName);
                        }
                    }
                }
            }

            // 将数据写入 Excel
            for (Map.Entry<String, List<GroupInfo>> entry : groupInfoMap.entrySet()) {
                String gdgsName = entry.getKey();
                List<GroupInfo> groupInfos = entry.getValue();

                // 统计每个供电所下的社区名称数量
                Map<String, Integer> gdsGroupCountMap = new HashMap<>();
                for (GroupInfo groupInfo : groupInfos) {
                    String gdsName = groupInfo.gdsName;
                    gdsGroupCountMap.put(gdsName, gdsGroupCountMap.getOrDefault(gdsName, 0) + 1);
                }

                // 找到对应的 sheet
                Sheet sheet = hssfWorkbook.getSheet(gdgsName);
                if (sheet == null) {
                    sheet = hssfWorkbook.createSheet(gdgsName);
                }

                Row row = sheet.getRow(0);
                Cell cell = row.getCell(0);
                String stringCellValue = cell.getStringCellValue();
                cell.setCellValue(stringCellValue.replace("date", DateUtil.today()));

                // 从第 3 行开始写入数据
                int startRow = 2;
                for (int i = 0; i < groupInfos.size(); i++) {
                    GroupInfo groupInfo = groupInfos.get(i);
                    Row dataRow = sheet.getRow(startRow + i);
                    if (dataRow == null) {
                        dataRow = sheet.createRow(startRow + i);
                    }

                    Cell cell1 = dataRow.getCell(0); // 序号
                    if (cell1 == null) {
                        cell1 = dataRow.createCell(0);
                    }
                    cell1.setCellValue(i + 1);

                    Cell cell2 = dataRow.getCell(1); // 供电公司
                    if (cell2 == null) {
                        cell2 = dataRow.createCell(1);
                    }
                    cell2.setCellValue(gdgsName);

                    Cell cell3 = dataRow.getCell(2); // 供电所
                    if (cell3 == null) {
                        cell3 = dataRow.createCell(2);
                    }
                    cell3.setCellValue(groupInfo.gdsName);

                    Cell cell4 = dataRow.getCell(3); // 转发群数量
                    if (cell4 == null) {
                        cell4 = dataRow.createCell(3);
                    }
                    cell4.setCellValue(gdsGroupCountMap.get(groupInfo.gdsName));


                    Cell cell5 = dataRow.getCell(4); // 原图名称
                    if (cell5 == null) {
                        cell5 = dataRow.createCell(4);
                    }
                    cell5.setCellValue(groupInfo.imgName);

                    Cell cell6 = dataRow.getCell(5); // 社区名称
                    if (cell6 == null) {
                        cell6 = dataRow.createCell(5);
                    }
                    cell6.setCellValue(groupInfo.groupName);

                    Cell cell7 = dataRow.getCell(6); // 群人数
                    if (cell7 == null) {
                        cell7 = dataRow.createCell(6);
                    }

                    try {
                        int i1 = Integer.parseInt(groupInfo.groupSize);
                        cell7.setCellValue(i1);
                    } catch (NumberFormatException e) {
                        cell7.setCellValue(1);
                    }
                }

                // 合并供电公司单元格
                if (groupInfos.size() > 1) {
                    CellRangeAddress newRegion = new CellRangeAddress(startRow, startRow + groupInfos.size() - 1, 1, 1);
                    boolean overlap = false;
                    int numMergedRegions = sheet.getNumMergedRegions();
                    for (int i = 0; i < numMergedRegions; i++) {
                        CellRangeAddress existingRegion = sheet.getMergedRegion(i);
                        if (isOverlap(newRegion, existingRegion)) {
                            overlap = true;
                            break;
                        }
                    }
                    if (!overlap) {
                        sheet.addMergedRegion(newRegion);
                    }
                }

                // 合并相同供电所和转发群数量单元格
                int currentRow = startRow;
                while (currentRow < startRow + groupInfos.size()) {
                    GroupInfo currentGroupInfo = groupInfos.get(currentRow - startRow);
                    String currentGdsName = currentGroupInfo.gdsName;
                    int currentGroupCount = gdsGroupCountMap.get(currentGdsName);
                    int endRow = currentRow;
                    // 找到连续相同供电所名称和转发群数量的最后一行
                    while (endRow + 1 < startRow + groupInfos.size()
                            && groupInfos.get(endRow + 1 - startRow).gdsName.equals(currentGdsName)
                            && gdsGroupCountMap.get(groupInfos.get(endRow + 1 - startRow).gdsName) == currentGroupCount) {
                        endRow++;
                    }
                    // 如果有连续相同的供电所名称和转发群数量，且范围至少包含两个单元格，进行合并
                    if (endRow > currentRow) {
                        // 合并供电所单元格
                        CellRangeAddress gdsRegion = new CellRangeAddress(currentRow, endRow, 2, 2);
                        boolean gdsOverlap = false;
                        int numMergedRegions = sheet.getNumMergedRegions();
                        for (int i = 0; i < numMergedRegions; i++) {
                            CellRangeAddress existingRegion = sheet.getMergedRegion(i);
                            if (isOverlap(gdsRegion, existingRegion)) {
                                gdsOverlap = true;
                                break;
                            }
                        }
                        if (!gdsOverlap) {
                            sheet.addMergedRegion(gdsRegion);
                        }

                        // 合并转发群数量单元格
                        CellRangeAddress groupCountRegion = new CellRangeAddress(currentRow, endRow, 3, 3);
                        boolean groupCountOverlap = false;
                        numMergedRegions = sheet.getNumMergedRegions();
                        for (int i = 0; i < numMergedRegions; i++) {
                            CellRangeAddress existingRegion = sheet.getMergedRegion(i);
                            if (isOverlap(groupCountRegion, existingRegion)) {
                                groupCountOverlap = true;
                                break;
                            }
                        }
                        if (!groupCountOverlap) {
                            sheet.addMergedRegion(groupCountRegion);
                        }
                    }
                    currentRow = endRow + 1;
                }
            }

            // 保存修改后的 Excel 文件
            String excelFileName = "统计结果" + DateUtil.today().replaceAll("-", "") + ".xlsx"; // 你可以根据需要修改文件名
            File excelFile = new File(exportDir, excelFileName);
            try (FileOutputStream fos = new FileOutputStream(excelFile)) {
                hssfWorkbook.write(fos);
                System.out.println("Excel 文件保存成功：" + excelFile.getAbsolutePath());
            } catch (IOException e) {
                System.err.println("保存 Excel 文件时出错：" + e.getMessage());
                e.printStackTrace();
            }

            // 创建原文件文件夹
            File originalFilesDir = new File(exportDir, "原文件");
            if (!originalFilesDir.exists()) {
                originalFilesDir.mkdirs();
            }

            // 仅复制原文件到 原文件 文件夹
            copyOriginalFiles(extractDir, originalFilesDir, originalFilePaths);

            // 将 exportDir 压缩为 ZIP 格式
            String exportZipFilePath = exportDir.getAbsolutePath() + ".zip";
            File exportZipFile = new File(exportZipFilePath);
            try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(exportZipFile))) {
                zipDirectory(exportDir, exportDir, zipOut);
            }

            zipFile.close();
            // 删除临时文件
            tempFile.delete();
        } catch (IOException e) {
            throw new Exception("处理 ZIP 文件时出错: " + e.getMessage(), e);
        } finally {
            errorLogWriter.close();
        }
    }

    private void zipDirectory(File sourceDir, File baseDir, ZipOutputStream zipOut) throws IOException {
        File[] files = sourceDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    zipDirectory(file, baseDir, zipOut);
                } else {
                    String entryName = file.getAbsolutePath().substring(baseDir.getAbsolutePath().length() + 1);
                    zipOut.putNextEntry(new ZipEntry(entryName));
                    try (InputStream in = new FileInputStream(file)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            zipOut.write(buffer, 0, bytesRead);
                        }
                    }
                    zipOut.closeEntry();
                }
            }
        }
    }

    private void copyOriginalFiles(File sourceDir, File destDir, Set<String> originalFilePaths) throws IOException {
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File[] files = sourceDir.listFiles();
        if (files != null) {
            boolean hasFiles = false;
            for (File file : files) {
                if (file.isDirectory()) {
                    File newDestDir = new File(destDir, file.getName());
                    copyOriginalFiles(file, newDestDir, originalFilePaths);
                    // 检查子目录复制后是否为空
                    if (newDestDir.listFiles() != null && newDestDir.listFiles().length > 0) {
                        hasFiles = true;
                    }
                } else {
                    if (originalFilePaths.contains(file.getAbsolutePath())) {
                        try (InputStream in = new FileInputStream(file);
                             OutputStream out = new FileOutputStream(new File(destDir, file.getName()))) {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = in.read(buffer)) != -1) {
                                out.write(buffer, 0, bytesRead);
                            }
                        }
                        hasFiles = true;
                    }
                }
            }
            // 如果当前目录没有文件（包括子目录也没有文件），则删除该目录
            if (!hasFiles) {
                destDir.delete();
            }
        }
    }



    private boolean isOverlap(CellRangeAddress range1, CellRangeAddress range2) {
        boolean rowOverlap = (range1.getFirstRow() <= range2.getLastRow()) && (range1.getLastRow() >= range2.getFirstRow());
        boolean colOverlap = (range1.getFirstColumn() <= range2.getLastColumn()) && (range1.getLastColumn() >= range2.getFirstColumn());
        return rowOverlap && colOverlap;
    }

    public static Workbook getWorkbook(String filePath) {
        InputStream is = null;
        Workbook wb = null;
        try {
            ResourceFileUtils resourceFileUtils = new ResourceFileUtils();
            is = resourceFileUtils.getResourceInputStream(filePath);
            if (isExcel2007(filePath)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            return wb;
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                }

            }
        }

    }


    /**
     * 描述：是否是2007的excel，返回true是2007
     *
     * @param filePath
     * @return
     */
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }


    private boolean isImageFile(String fileName) {
        String lowerCaseFileName = fileName.toLowerCase();
        return lowerCaseFileName.endsWith(".jpg") || lowerCaseFileName.endsWith(".jpeg")
                || lowerCaseFileName.endsWith(".png") || lowerCaseFileName.endsWith(".gif");
    }


    /**
     * 图片解析
     *
     * @param imagePath
     */
    public String imgParser(String imagePath) {
        String resStr = null;

        try {
            BufferedImage originalImage = loadImageFromFile(imagePath);
            // 假设截取顶部高度为图像高度的1/10，宽度为图像宽度
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();
            int topHeight = height / 10;
            BufferedImage topImage = originalImage.getSubimage(0, 0, width, topHeight);

//            // 假设从剩余部分宽度的起始位置开始截取一定宽度
//            int remainingWidthStart = 200; // 可以根据实际情况调整起始位置
//            int remainingWidth = 300; // 可以根据实际情况调整截取宽度
//            BufferedImage croppedImage = topImage.getSubimage(remainingWidthStart, 0, remainingWidth, topHeight);

            // 初始化推理引擎
            InferenceEngine engine = InferenceEngine.getInstance(Model.ONNX_PPOCR_V4);

            // 将 BufferedImage 保存为文件并获取文件路径
            String savedImagePath = saveImageToFile(topImage);

            // 运行 OCR 并获取结果
            OcrResult ocrResult = engine.runOcr(savedImagePath);
//            System.out.println("识别结果为" + ocrResult);

            deleteImageFile(savedImagePath);

            String res = ocrResult.getStrRes().trim().replaceAll(" ", "");

            System.out.println("ocr result=== " + res);
            String[] lines = res.split("\n");

            Pattern pattern = Pattern.compile("(.*?)(\\(|（)(\\d+)(\\)|）)");

            for (String line : lines) {
                String processedLine = processLine(line);

                Matcher matcher = pattern.matcher(processedLine);
                if (matcher.find()) {

                    String groupName = matcher.group(1).trim();

                    if (ObjectUtil.isEmpty(groupName)) {
                        groupName = "未识别出群名";
                    }

                    String groupSize = matcher.group(3).trim();
                    if (ObjectUtil.isEmpty(groupSize)) {
                        groupSize = "1";
                    }

                    // 验证 groupSize 是否为有效的数字
                    try {
                        Integer.parseInt(groupSize);
                    } catch (NumberFormatException e) {
                        groupSize = "1";
                    }

                    System.out.println("群名: " + groupName + ", 群人数: " + groupSize);

                    String invalidChars = "[\\\\/:*?\"<>|]";
                    groupName = groupName.replaceAll(invalidChars, "");

                    resStr = groupName + "_" + groupSize;
                }
            }

            if (ObjectUtil.isEmpty(resStr)) {
                String groupName = "";
                String groupSize = "1";
                for (String line : lines) {
                    // 没有匹配上括号，尝试拿后面是中文的汉字
                    groupName = extractChineseCharacters(line);
                    if (groupName.isEmpty()) {
                        groupName = line;
                    }
                    groupSize = "1";

                    groupName = line;
                }

                String invalidChars = "[\\\\/:*?\"<>|]";
                groupName = groupName.replaceAll(invalidChars, "");

                System.out.println("群名: " + groupName + ", 群人数: " + groupSize);
                resStr = groupName + "_" + groupSize;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resStr;
    }

    /**
     * 识别完成后删除图片文件
     *
     * @param filePath 图片文件路径
     */
    private static void deleteImageFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("图片文件已成功删除: " + filePath);
            } else {
                System.out.println("删除图片文件失败: " + filePath);
            }
        } else {
            System.out.println("图片文件不存在: " + filePath);
        }
    }

        public static void main(String[] args) {
            String groupName = "东樊各庄樊情一家\\";
            String invalidChars = "[\\\\/:*?\"<>|]";
            String filteredName = groupName.replaceAll(invalidChars, "");
            System.out.println(filteredName);
        }

    private static String extractChineseCharacters(String input) {
        StringBuilder chineseChars = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN) {
                chineseChars.append(c);
            }
        }
        return chineseChars.toString();
    }

    private static String processLine(String line) {
        // 去除尖括号
        line = line.replaceAll("[<>]", "");
        // 去除首尾空格并替换中间的空格
        String processed = line.trim().replaceAll(" ", "");

        boolean hasLeftParenthesis = processed.contains("（") || processed.contains("(");
        boolean hasRightParenthesis = processed.contains("）") || processed.contains(")");

        // 只有当存在左括号或右括号时才补全
        if (hasLeftParenthesis || hasRightParenthesis) {
            // 检查是否缺少左括号
            if (!hasLeftParenthesis) {
                int numIndex = findFirstDigitIndex(processed);
                if (numIndex > 0) {
                    processed = processed.substring(0, numIndex) + "（" + processed.substring(numIndex);
                }
            }

            // 检查是否缺少右括号
            if (!hasRightParenthesis) {
                int numIndex = findLastDigitIndex(processed);
                if (numIndex < processed.length() - 1) {
                    processed = processed.substring(0, numIndex + 1) + "）" + processed.substring(numIndex + 1);
                }
            }
        }

        return processed;
    }

    private static int findFirstDigitIndex(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {
                return i;
            }
        }
        return -1;
    }

    private static int findLastDigitIndex(String str) {
        for (int i = str.length() - 1; i >= 0; i--) {
            if (Character.isDigit(str.charAt(i))) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 从本地文件加载图片并转换为BufferedImage
     *
     * @param imagePath 图片的本地路径
     * @return BufferedImage对象
     * @throws IOException 如果读取图片时出错
     */
    private static BufferedImage loadImageFromFile(String imagePath) throws IOException {
        return ImageIO.read(new File(imagePath));
    }

    /**
     * 将 BufferedImage 保存为文件并返回文件路径
     *
     * @param image BufferedImage 对象
     * @return 文件路径
     * @throws IOException 如果保存文件时出错
     */
    private static String saveImageToFile(BufferedImage image) throws IOException {
        // 获取当前时间戳
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = dateFormat.format(new Date());
        // 构建带有时间戳的文件名
        String fileName = "temp_top_image_" + timestamp + ".jpg";
        File output = new File(fileName);

        // 先尝试直接保存
        try {
            ImageIO.write(image, "jpg", output);
            if (output.exists() && output.length() > 0) {
                return output.getAbsolutePath();
            }
        } catch (IOException e) {
            // 直接保存失败，尝试转换图像类型后保存
        }

        // 尝试转换为支持的类型（这里以 TYPE_INT_RGB 为例，去除透明度）
        BufferedImage convertedImage = convertToSupportedType(image, BufferedImage.TYPE_INT_RGB);
        try {
            ImageIO.write(convertedImage, "jpg", output);
            if (output.exists() && output.length() > 0) {
                return output.getAbsolutePath();
            }
        } catch (IOException e) {
            // 转换类型后保存仍失败，抛出异常
            throw new IOException("图片保存失败，即使转换类型后仍无法保存", e);
        }

        // 如果还是保存失败，抛出异常
        throw new IOException("图片保存失败，文件可能为空或不存在");
    }

    /**
     * 将 BufferedImage 转换为指定类型
     *
     * @param sourceImage 源图像
     * @param targetType  目标类型
     * @return 转换后的图像
     */
    private static BufferedImage convertToSupportedType(BufferedImage sourceImage, int targetType) {
        BufferedImage convertedImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), targetType);
        Graphics2D g2d = convertedImage.createGraphics();
        if (targetType == BufferedImage.TYPE_INT_RGB) {
            // 如果目标类型是 RGB（不支持透明度），填充白色背景
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, convertedImage.getWidth(), convertedImage.getHeight());
        }
        g2d.drawImage(sourceImage, 0, 0, null);
        g2d.dispose();
        return convertedImage;
    }

}
